{% extends "base.html" %}

{% block content %}
<div class="container">
    <h2>My Files</h2>
    
    <div class="file-upload-section mb-4">
        <form id="upload-form" method="post" enctype="multipart/form-data" action="{% url 'media:upload' %}">
            {% csrf_token %}
            <input type="file" name="file" required>
            <button type="submit" class="btn btn-primary">Upload</button>
        </form>
    </div>

    <div class="file-list">
        {% for file in files %}
        <div class="file-item card mb-3">
            <div class="card-body">
                <h5 class="card-title">{{ file.filename }}</h5>
                <p class="card-text">
                    Size: {{ file.size|filesizeformat }}<br>
                    Uploaded: {{ file.uploaded_at }}<br>
                    Owner: {{ file.owner.username }}
                </p>
                <div class="btn-group">
                    <a href="{{ file.file.url }}" class="btn btn-sm btn-primary" target="_blank">Download</a>
                    {% if request.user == file.owner or request.user.is_superuser %}
                    <button class="btn btn-sm btn-danger delete-file" data-file-id="{{ file.id }}">Delete</button>
                    <button class="btn btn-sm btn-info manage-permissions" data-file-id="{{ file.id }}">Permissions</button>
                    {% endif %}
                </div>
            </div>
        </div>
        {% empty %}
        <p>No files found.</p>
        {% endfor %}
    </div>
</div>

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Handle file deletion
    document.querySelectorAll('.delete-file').forEach(button => {
        button.addEventListener('click', function() {
            if (confirm('Are you sure you want to delete this file?')) {
                const fileId = this.dataset.fileId;
                fetch(`/media/files/${fileId}/delete/`, {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                    }
                }).then(response => {
                    if (response.ok) {
                        location.reload();
                    }
                });
            }
        });
    });
});
</script>
{% endblock %}
{% endblock %}
